package bibliotheque.server;

import bibliotheque.wave.WaveAction;
import bibliotheque.wave.WaveAgent;

public class HelloAction extends WaveAction {
    
    private long timeout;
    
    public HelloAction(long timeout) {
        this.timeout = timeout;
    }
    
    public void PropagateBefore(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                
                if(server.timertask_hellotimeout != null) server.timertask_hellotimeout.cancel();
                server.timertask_hellotimeout = server.new TimertaskHelloTimeout();
                server.timer_hellotimeout.schedule(server.timertask_hellotimeout, timeout);
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
            } finally {
                server.mutex.release();
            }
        }
    }
    
    public void LocalEnd(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                
                if(server.state == Server.State.STOPPING && server.transaction_manager.GetNbUseDocument() == 0 && server.GetNbWaves() == 0) {
                    server.state = Server.State.STOP;
                    server.StateChanged(server.state.toString());
                }
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
            } finally {
                server.mutex.release();
            }
        }
    }
    
    public void GlobalEnd(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                
                server.name_server.Hello();
            } catch (Exception ex) {
                server.ErrorOccured("Hello failed cause the nameserver returned an error.");
            } finally {
                server.mutex.release();
            }
        }
    }
}
